/**
 * Ant Design 响应式组件封装
 *
 * 解决已知的移动端兼容性问题
 */

import React from 'react';
import { Drawer, Modal, Table, Select, Dropdown } from 'antd';
import type { DrawerProps, ModalProps, TableProps, SelectProps, DropdownProps } from 'antd';
import { useBreakpoint } from '../../hooks/useBreakpoint';

/**
 * 响应式Drawer
 *
 * 移动端自动全屏显示
 */
export const ResponsiveDrawer: React.FC<DrawerProps> = (props) => {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  return (
    <Drawer
      {...props}
      width={isMobile ? '100%' : props.width}
      height={isMobile && props.placement === 'bottom' ? '85%' : props.height}
      placement={isMobile ? 'bottom' : props.placement}
    />
  );
};

/**
 * 响应式Modal
 *
 * 移动端优化显示尺寸和位置
 */
export const ResponsiveModal: React.FC<ModalProps> = (props) => {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  return (
    <Modal
      {...props}
      width={isMobile ? '90%' : props.width}
      centered={isMobile ? true : props.centered}
      style={{
        ...props.style,
        ...(isMobile && { top: 20, paddingBottom: 0 })
      }}
    />
  );
};

/**
 * 响应式Table
 *
 * 移动端启用横向滚动
 */
export function ResponsiveTable<T extends object>(props: TableProps<T>) {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  return (
    <Table
      {...props}
      scroll={{
        ...props.scroll,
        x: isMobile ? 'max-content' : props.scroll?.x
      }}
      pagination={
        isMobile
          ? {
              ...(typeof props.pagination === 'object' ? props.pagination : {}),
              simple: true,
              size: 'small',
            }
          : props.pagination
      }
      size={isMobile ? 'small' : props.size}
    />
  );
}

/**
 * 响应式Select
 *
 * 移动端优化下拉菜单显示
 */
export const ResponsiveSelect: React.FC<SelectProps> = (props) => {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  return (
    <Select
      {...props}
      listHeight={isMobile ? 300 : props.listHeight}
      placement={isMobile ? 'bottomLeft' : props.placement}
      dropdownStyle={{
        ...props.dropdownStyle,
        ...(isMobile && { maxHeight: '50vh' })
      }}
    />
  );
};

/**
 * 响应式Dropdown
 *
 * 移动端转换为底部Sheet样式
 */
export const ResponsiveDropdown: React.FC<DropdownProps> = (props) => {
  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  return (
    <Dropdown
      {...props}
      placement={isMobile ? 'bottom' : props.placement}
      trigger={isMobile ? ['click'] : props.trigger}
    />
  );
};

/**
 * 统一导出
 */
export const ResponsiveAntd = {
  Drawer: ResponsiveDrawer,
  Modal: ResponsiveModal,
  Table: ResponsiveTable,
  Select: ResponsiveSelect,
  Dropdown: ResponsiveDropdown,
};
